// src/pages/home/widgets/doctors/index.tsx
import styles from "@styles/home.module.scss";
import { useLazyRequestDoctorsQuery } from "@store/apiSlice/doctorApiSlice";
import { useState } from "react";
import { useTypedDispatch, useTypedSelector } from "@store/index";
import { doctorSelectors, saveDoctors } from "@store/slices/doctorSlice";
import Infinite from "@shared/infinite";
import FocusDoctor from "@pages/home/widgets/doctors/focusDoctor";
export default function Doctors() {
    // 用于获取推荐医生列表
    const [requestDoctors] = useLazyRequestDoctorsQuery();
    // 页码
    const [current, setCurrent] = useState(1);
    // 是否有更多数据可以加载
    const [hasMore, setHasMore] = useState(true);
    // 每页加载数据条数
    const [pageSize] = useState(10);
    // 获取 dispatch 方法
    const dispatch = useTypedDispatch();
    // 获取推荐医生列表
    const doctors = useTypedSelector(doctorSelectors.selectAll);
    // 无限列表加载
    const loadMore = async () => {
        return requestDoctors({ current, pageSize })
            .unwrap()
            .then(({ data: { rows, pageTotal } }) => {
                // 保存状态医生列表
                dispatch(saveDoctors(rows));
                // 表示是否还有更多数据的布尔值
                const hasMore = current < pageTotal;
                // 更新页码
                if (hasMore) setCurrent((prev) => prev + 1);
                // 是否还有更多数据
                setHasMore(hasMore);
            });
    };

    return (
        <div className={styles.focus}>
            <div className={styles.top}>
                <h4>推荐关注</h4>
                <a href="#">查看更多 &gt;</a>
            </div>
            <div className={styles.container}>
                <div className={styles.inner}>
                    {doctors.map((doctor) => (
                        <div className={styles.item} key={doctor.id}>
                            <img src={doctor.avatar} alt="" className={styles.avatar} />
                            <span className={styles.doctor}>{doctor.name}</span>
                            <span className={styles.hospital}>
                {doctor.hospitalName} {doctor.depName}
              </span>
                            <span className={styles.job}>{doctor.positionalTitles}</span>
                            <FocusDoctor doctor={doctor}></FocusDoctor>
                        </div>
                    ))}
                    <Infinite direction="horizontal" loadMore={loadMore} hasMore={hasMore} />
                </div>
            </div>
        </div>
    );
}